import { defineStore } from 'pinia'
import { login, getCurrentUser } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userRole: (state) => state.userInfo?.roleCode || null,
    hasAdminAccess: (state) => state.userInfo?.roleCode === 'ADMIN',
    hasMaintenanceAccess: (state) => ['ADMIN', 'MAINTENANCE'].includes(state.userInfo?.roleCode),
    canManageFacilities: (state) => ['ADMIN', 'MAINTENANCE'].includes(state.userInfo?.roleCode)
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        console.log('🔐 =================================')
        console.log('🔐 开始登录流程')
        console.log('🔐 登录表单:', loginForm)
        console.log('🔐 当前store token:', this.token)
        console.log('🔐 当前localStorage token:', localStorage.getItem('token'))
        
        const response = await login(loginForm)
        console.log('🔐 登录API响应:', response)
        console.log('🔐 响应数据类型:', typeof response.data)
        console.log('🔐 响应数据长度:', response.data ? response.data.length : 0)
        
        this.token = response.data
        localStorage.setItem('token', this.token)
        
        console.log('🔐 Token已保存到store:', this.token)
        console.log('🔐 Token已保存到localStorage:', localStorage.getItem('token'))
        console.log('🔐 Store isLoggedIn状态:', this.isLoggedIn)
        console.log('🔐 Token保存后验证 - localStorage有token:', !!localStorage.getItem('token'))
        console.log('🔐 登录流程完成')
        console.log('🔐 =================================')
        
        // 登录成功后获取用户信息
        await this.fetchUserInfo()
        
        return response
      } catch (error) {
        console.error('❌ 登录失败:', error)
        console.error('❌ 错误详情:', error.response?.data || error.message)
        throw error
      }
    },

    // 登出
    logout() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('token')
    },

    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        if (!this.token) {
          return
        }
        const response = await getCurrentUser()
        this.userInfo = response.data
        console.log('👤 用户信息获取成功:', this.userInfo)
      } catch (error) {
        console.error('❌ 获取用户信息失败:', error)
        // 如果获取用户信息失败，清除token
        this.logout()
      }
    }
  }
})